package com.caiden_micheal.user.aop;


import com.caiden_micheal.base.aop.annotation.PermissionVerify;
import com.caiden_micheal.base.domain.AjxResult;
import com.caiden_micheal.base.utils.BaseContext;
import com.caiden_micheal.user.service.UserService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;

@Aspect
@Component
public class PermissionAspect {
    @Autowired
    private UserService userService;

    @Pointcut("@annotation(com.caiden_micheal.base.aop.annotation.PermissionVerify)")
    public void permissionCut() {
    }

    @Around("permissionCut()")
    public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        PermissionVerify annotation = method.getAnnotation(PermissionVerify.class);
        String[] permissionArray = annotation.permissionArray();
        List<String> authNameList = userService.findUserAuthorityNameListByUserId(Long.valueOf(BaseContext.getInfo().get("userId").toString()), false);
        if (CollectionUtils.containsAny(authNameList, Arrays.asList(permissionArray))) {
            return joinPoint.proceed();
        }
        return AjxResult.unAuthorizedAccess("当前用户无权访问");
    }
}
